import datetime

from sqlalchemy import String, BigInteger
from sqlalchemy.dialects.mysql import INTEGER, DATETIME

from shop.model import db
from shop.util.mylogger import KLogger
from shop.util.time_operation import TimeClass


class Goods(db.Model):
    __tablename__ = 'goods'

    id = db.Column(INTEGER(20), primary_key=True)
    goods_info = db.Column(String(4096))
    goods_id = db.Column(BigInteger, index=True)
    create_time = db.Column(DATETIME)
    view_time = db.Column(DATETIME)

    def to_json(self):
        return {
            "goods_id": self.goods_id,
            "goods_info": self.goods_info,
            "create_time": TimeClass.get_str_by_datetime(self.create_time),
            "view_time": TimeClass.get_str_by_datetime(self.view_time)
        }

    @staticmethod
    def save_goods(goods_id, goods_info):
        '''
        保存商品
        :param goods_id:
        :param goods_info:
        :return:
        '''
        goods_id = int(goods_id)
        now_time = datetime.datetime.now()
        # 首先查询，如果存在就更新时间
        one_goods = db.session.query(Goods).filter(Goods.goods_id == goods_id).first()
        if one_goods:
            one_goods.view_time = now_time
        else:
            # 不存在就创建
            g = Goods()
            g.goods_id = goods_id
            g.goods_info = goods_info
            g.create_time = now_time
            g.view_time = now_time
            db.session.add(g)
        # 提交保存
        try:
            db.session.commit()
        except Exception as e:
            KLogger.error("保存或更新商品信息报错：{}".format(str(e)))
            db.session.rollback()
            db.session.remove()
        finally:
            db.session.close()

    @staticmethod
    def get_goods_by_goods_id_list(goods_id_list):
        '''
        根据goods_id列表获取一些商品
        :param goods_id_list:
        :return:
        '''
        goods_list = db.session.query(Goods).filter(Goods.goods_id.in_(goods_id_list)).order_by(
            Goods.view_time.desc()).all()
        return goods_list
